package main.service;

import main.dao.VoteDAO;
import main.entity.VoteOptionVO;
import main.entity.VoteVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service("voteOptionService")
public class VoteOptionService extends BaseService<VoteOptionVO> {
	
	@Autowired
	private VoteDAO voteDAO;
	
	public Boolean updateByID(Integer optID, Integer uID){//get uID from session better
		Boolean isUpdate  = true;
		VoteOptionVO optionVO = getBaseDAO().getByID(VoteOptionVO.class, optID);
		Integer voteID = optionVO.getVoteID();
		VoteVO voteVO = voteDAO.getByID(VoteVO.class, voteID);
		String hasVotedUsersString = voteVO.getHasVotedUsers();
		
		if (!StringUtils.isEmpty(hasVotedUsersString)) {
			String[]hasVotedUsersArray = hasVotedUsersString.split(",");
			for (String userID : hasVotedUsersArray) {
				if (uID.equals(userID)) {
					isUpdate=false;
				}
			}
		} else {//no one has voted before
			optionVO.setTicketNum(optionVO.getTicketNum() + 1);
			getBaseDAO().update(optionVO);
			voteVO.setHasVotedUsers(voteVO.getHasVotedUsers()+uID+",");//record the user who has vote this vote
		}	
		
		return isUpdate;
	}
	
}
